package cn.connectivity.plugin.gui.dialog;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.ui.components.JBLabel;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Objects;

public class SettingsSelectDialogWrapper extends DialogWrapper {

    private static SettingsSelectDialogWrapper INSTANCE;

    public static SettingsSelectDialogWrapper getInstance() {
        if(Objects.isNull(INSTANCE)) {
            INSTANCE = new SettingsSelectDialogWrapper();
        }
        if(INSTANCE.isDisposed()) {
            INSTANCE = new SettingsSelectDialogWrapper();
        }
        return INSTANCE;
    }
    protected SettingsSelectDialogWrapper() {
        super(true);
        init();
    }

    @Override
    protected @Nullable JComponent createTitlePane() {
        return new JBLabel("配置选择");
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return SettingsSelectDialog.getInstance().getTablePanel();
    }

    private CustomOKAction okAction;
    private DialogWrapperExitAction exitAction;

    /**
     * 校验数据
     * @return 通过必须返回null，不通过返回一个 ValidationInfo 信息
     */
    @Nullable
    @Override
    protected ValidationInfo doValidate() {
        JTable dataTable = SettingsSelectDialog.getInstance().getDataTable();
        int selectedRow = dataTable.getSelectedRow();
        if(selectedRow == 1) {
            return null;
        } else {
            return new ValidationInfo("请选择需要配置");
        }
    }

    /**
     * 覆盖默认的ok/cancel按钮
     * @return
     */
    @NotNull
    @Override
    protected Action[] createActions() {
        exitAction = new DialogWrapperExitAction("取消", CANCEL_EXIT_CODE);
        okAction = new CustomOKAction();
        // 设置默认的焦点按钮
        okAction.putValue(DialogWrapper.DEFAULT_ACTION, true);
        return new Action[]{okAction,exitAction};
    }


    /**
     * 自定义 ok Action
     */
    protected class CustomOKAction extends DialogWrapperAction {

        protected CustomOKAction() {
            super("确定");
        }

        @Override
        protected void doAction(ActionEvent e) {
            // 点击ok的时候进行数据校验
            ValidationInfo validationInfo = doValidate();
            if (validationInfo != null) {
                Messages.showMessageDialog(validationInfo.message,"校验不通过", Messages.getInformationIcon());
            } else {

                close(CANCEL_EXIT_CODE);
            }
        }
    }
}
